<template>
  <!-- 搜索框 -->
  <div style="flex: inherit">
    <el-form ref="queryForm" :inline="true" :model="queryParams">
      <el-form-item label="名称" prop="name">
        <el-input
            v-model="queryParams.name"
            clearable
            maxlength="50"
            placeholder="请输入姓名"
            show-word-limit
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
      <el-button :icon="Search" type="primary" @click="handleQuery">搜 索</el-button>
        <el-button :icon="CircleClose" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <div style="margin-bottom: 10px">
      <el-button type="primary" :icon="CirclePlus" @click="openDialog(null)">新 增</el-button>
      <el-button type="danger" :icon="Delete" @click="batchDelete">批量删除</el-button>
      <el-button type="primary" style="float: right" :icon="RefreshLeft" @click="revocation">撤 销</el-button>
    </div>

    <!-- 表格 -->
    <el-table
        ref="multipleTableRef"
        :data="tableData"
        v-loading="loading"
        style="width: 1300px; box-shadow: 1px 1px 1px 1px gray;"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column property="name" label="姓名" width="120" align="center" />
      <el-table-column property="age" label="年龄" width="60" align="center" />
      <el-table-column property="sex" label="性别" width="60" align="center">
        <template #default="scope">
          <el-tag v-if="scope.row.sex === 0">男</el-tag>
          <el-tag class="ml-2" type="success" v-else>女</el-tag>
        </template>
      </el-table-column>
      <el-table-column property="phoneNumber" label="联系电话" width="120" align="center" />
      <el-table-column label="创建日期" width="160" align="center">
        <template #default="scope">{{ scope.row.createTime }}</template>
      </el-table-column>
      <el-table-column property="detailAddress" label="详细地址" show-overflow-tooltip width="500" align="center" />
      <!-- 操作栏 -->
      <el-table-column fixed="right" label="操作栏" width="150">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="detail(scope.row)">详情</el-button>
          <el-button link type="primary" size="small" @click="openDialog(scope.row)">编辑</el-button>
          <el-popconfirm
              width="220"
              confirm-button-text="是"
              cancel-button-text="否"
              :icon="InfoFilled"
              icon-color="#626AEF"
              title="确定删除吗?"
              @confirm="singleDelete(scope.row.userId)"
          >
            <template #reference>
              <el-button link type="primary" size="small">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="pagination" style="margin-top: 10px; float: right">
      <el-pagination
          background
          layout="total, sizes, prev, pager, next"
          :current-page="tablePage.pageNum"
          :page-size="tablePage.pageSize"
          :page-sizes="tablePage.pageSizes"
          :total="tablePage.total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
      />
    </div>
  </div>

  <!-- 新增/编辑 -->
  <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle.title"
      width="50%"
      :before-close="handleClose"
  >
    <el-form :inline="true" style="display: inline" :rules="rules" :model="UserForm" ref="ruleFormRef" >
      <el-form-item label="姓名" prop="name">
        <el-input v-model="UserForm.name" placeholder="请选择姓名" />
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-select v-model="UserForm.sex" placeholder="请选择性别">
          <el-option label="男" value="0" />
          <el-option label="女" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="年龄" prop="age">
        <el-input-number v-model="UserForm.age" :min="1" />
      </el-form-item>
      <el-form-item label="联系电话" prop="phoneNumber">
        <el-input v-model="UserForm.phoneNumber" placeholder="请选择联系电话" />
      </el-form-item>
      <el-form-item label="省/市/区">
          <elui-china-area-dht placeholder="请选择地址" v-model="chinaAreaDht" :leave="3" @change="onChange"></elui-china-area-dht>
          <el-input v-model="UserForm.detailAddress" placeholder="详情地址" style="width: 300px" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelForm">取 消</el-button>
        <el-button type="primary" v-if="submitButton" @click="onSubmit(ruleFormRef)">提 交</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import {Delete, CirclePlus, InfoFilled, Search, CircleClose, RefreshLeft} from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import { EluiChinaAreaDht } from 'elui-china-area-dht'
import {reactive, Ref, ref, onMounted} from 'vue'
import {ElMessage, ElTable} from 'element-plus'
import { ElMessageBox } from 'element-plus'
import request from '@/utils/request'

/** 组件初始化 */
onMounted(() => {
  const name = localStorage.getItem("queryParam")
  const pageNum = Number(localStorage.getItem("currentPage"))
  const pageSize = Number(localStorage.getItem("currentSize"))
  if (name != null) {
    queryParams.name = name
  }
  if (pageNum != null && pageNum != 0) {
    tablePage.pageNum = pageNum
  }
  if (pageSize != null && pageSize != 0) {
    tablePage.pageSize = pageSize
  }
  pageUser()
})

/** 地址选择器的value值 */
const chinaAreaDht = reactive([]);
const chinaData = new EluiChinaAreaDht.ChinaArea().chinaAreaflat
// 覆盖区县
const onChange = (e:any) => {
  const province = chinaData[e[0]]
  const city = chinaData[e[1]]
  const area = chinaData[e[2]]
  UserForm.addressValue = province.value + "," + city.value + "," + area.value
  UserForm.province = province.label
  UserForm.city = city.label
  UserForm.district = area.label
}

/** 表格信息 */
interface User {
  userId: number
  name: string
  sex: number
  age: number
  phoneNumber: string
  createTime: string
  detailAddress: string
}
const loading = ref(false)

/** 表单信息 */
const UserForm = reactive({
  userId: null,
  name: '',
  sex: null,
  age: 1,
  phoneNumber: '',
  createTime: '',
  detailAddress: '',
  province: '',
  city: '',
  district: '',
  addressValue: ''
})
const ruleFormRef = ref<FormInstance>()

/** 搜索参数 */
const queryParams = reactive({
  name: ''
})

/** 分页参数 */
const tablePage = reactive({
  pageNum: 1,
  pageSize: 10,
  pageSizes: [10, 20, 30],
  total: 0
})

/** 表格数据 */
const tableData: Ref<User> = ref()
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelection = ref<User[]>([])
const handleSelectionChange = (val: User[]) => {
  multipleSelection.value = val
}
// 分页查询用户信息
const pageUser = () => {
  loading.value = true
  request({
    url: '/user',
    data: Object.assign(queryParams, {current: tablePage.pageNum, size: tablePage.pageSize}),
    method: 'get'
  }).then(res => {
    tableData.value = res.data.records
    tablePage.pageNum = res.data.current
    tablePage.pageSize = res.data.size
    tablePage.total = res.data.total
    loading.value = false
  })
}

/** 查询用户详情 */
const detail = (row) => {
  dialogTitle.title = "用户详情"
  dialogVisible.value = true
  submitButton.value = false
  request({
    url: '/user/detail',
    data : {userId: row.userId},
    method: 'get'
  }).then(res => {
    UserForm.userId = res.data.userId
    UserForm.name = res.data.name
    UserForm.sex = res.data.sex.toString()
    UserForm.age = res.data.age
    UserForm.phoneNumber = res.data.phoneNumber
    UserForm.detailAddress = res.data.detailAddress
    if (res.data.addressValue != null) {
      res.data.addressValue.split(",").map(item => {
        chinaAreaDht.push(item)
      })
    }
  })
}

/** 新增或编辑 弹窗操作 */
const submitButton = ref(true)
const dialogVisible = ref(false)
const handleClose = (done: () => void) => {
  cleanUserForm()
  done()
}
// 取消提交
const cancelForm = () => {
  cleanUserForm()
  dialogVisible.value = false
}
// 清空弹出表单数据
const cleanUserForm = () => {
  // 清空地址选择器
  chinaAreaDht.length = 0
  UserForm.userId = null
  UserForm.name = ''
  UserForm.sex = null
  UserForm.age = null
  UserForm.phoneNumber = ''
  UserForm.createTime = ''
  UserForm.detailAddress = ''
  UserForm.province = ''
  UserForm.city = ''
  UserForm.district = ''
}
// 弹窗标题
const dialogTitle = reactive({
  title: ''
});
const openDialog = (data) => {
  submitButton.value = true
  // 清空地址选择器
  chinaAreaDht.length = 0
  if (data != null) {
    dialogTitle.title = "编辑用户"
    UserForm.userId = data.userId;
    UserForm.name = data.name;
    UserForm.phoneNumber = data.phoneNumber;
    UserForm.sex = data.sex;
    UserForm.age = data.age;
    UserForm.detailAddress = data.detailAddress;
    UserForm.addressValue = data.addressValue;
    if (data.addressValue != null) {
      data.addressValue.split(",").map(item => {
        chinaAreaDht.push(item)
      });
    }
  } else {
    dialogTitle.title = "新增用户"
    cleanUserForm()
  }
  dialogVisible.value = true;
}

/** 提交 新增/编辑信息 */
const onSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      UserForm.detailAddress = UserForm.province + UserForm.city + UserForm.district + UserForm.detailAddress;
      if (UserForm.userId == null) {
        request({
          url: '/user',
          data : UserForm,
          method: 'post'
        }).then(res => {
          if (res.code == 200) {
            ElMessage({
              message: '新增成功！',
              type: 'success',
            })
            // 刷新表格
            pageUser()
            dialogVisible.value = false
          }
        })
      } else {
        request({
          url: '/user',
          data : UserForm,
          method: 'put'
        }).then(res => {
          if (res.code == 200) {
            ElMessage({
              message: '编辑成功！',
              type: 'success',
            })
            // 刷新表格
            pageUser()
            dialogVisible.value = false
          }
        })
      }
    } else {
      return
    }
  })
}

/** 单个删除 */
const singleDelete = (data) => {
  loading.value = true
  const userIds = []
  userIds.push(data)
  request({
    url: '/user?userIds=' + userIds.join(","),
    method: 'delete'
  }).then(res => {
    if (res.code == 200) {
      ElMessage({
        message: '删除成功！',
        type: 'success',
      })
    }
    // 刷新表格
    pageUser()
  }).catch(() => {
    loading.value = false
  })
}

/** 批量删除 */
const batchDelete = () => {
  const length = multipleSelection.value.length
  if (length === 0) {
    ElMessage({
      message: '请至少选择一条要删除的用户信息',
      type: 'warning',
    })
    return
  }
  ElMessageBox.confirm(
      '确定要删除' + length + "条用户信息吗？",
      '警告',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        loading.value = true
        const userIds = [];
        multipleSelection.value.map(item => {
          userIds.push(item.userId)
        })
        request({
          url: '/user?userIds=' + userIds.join(","),
          method: 'delete'
        }).then(res => {
          if (res.code == 200) {
            ElMessage({
              message: '成功删除' + length + "条用户信息",
              type: 'success',
            })
          }
          // 刷新表格
          pageUser()
        }).catch(() => {
          loading.value = false
        })
      })
}

/** 撤销 */
const revocation = () => {
  ElMessageBox.confirm(
      '确定撤回上一次的操作吗?',
      '撤回',
      {
        confirmButtonText: '确定撤回',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        loading.value = true
        request({
          url: '/user/revocation',
          method: 'post'
        }).then(res => {
          if (res.code == 200) {
            ElMessage({
              message: '撤回成功！',
              type: 'success',
            });
          } else {
            ElMessage('没有撤回的记录或已经撤回！')
          }
          // 刷新表格
          pageUser();
        }).catch(() => {
          loading.value = false
        })
      })
}

/** 搜索按钮操作 */
const handleQuery = () => {
  setLocalStorage()
  pageUser()
};

/** 重置搜索按钮操作 */
const resetQuery = () => {
  queryParams.name = ''
  setLocalStorage()
  pageUser()
}

/** 总页数改变 */
const handleSizeChange = (val: number) => {
  tablePage.pageSize = val
  setLocalStorage()
  pageUser()
}

/** 下一页 */
const handlePageChange = (val: number) => {
  tablePage.pageNum = val
  setLocalStorage()
  pageUser()
}

/** 校验表单参数 */
const rules = reactive<FormRules>({
  name: [
    { required: true, message: '姓名不能为空', trigger: 'blur' }
  ],
  sex: [
    { required: true, message: '性别不能为空', trigger: 'blur' }
  ],
  age: [
    { required: true, message: '年龄不能为空', trigger: 'blur' }
  ],
  phoneNumber: [
    { required: true, message: '手机号码不能为空', trigger: 'blur' }
  ]
})

/** 存储操作记录 */
const setLocalStorage = () => {
  localStorage.setItem("queryParam", queryParams.name)
  localStorage.setItem("currentPage", tablePage.pageNum.toString())
  localStorage.setItem("currentSize", tablePage.pageSize.toString())
}
</script>

<style scoped>

</style>
